package aure.jslib;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

public class StaticHelper {
	/**
	 * Run the script at scriptLocation.
	 * 
	 * It will look for the script in the classpath.
	 * @param cx
	 * @param scriptLocation
	 * @param scope
	 */
	public static void runScript(Context cx, String scriptLocation, Scriptable scope)  {
		try {
			InputStream is = StaticHelper.class.getResourceAsStream(scriptLocation);
			Reader jsReader = new InputStreamReader(is);
			
			try {
				cx.evaluateReader(scope, jsReader, scriptLocation, 1, null);
			} finally {
				jsReader.close();
			}
		} catch (IOException e) {
			new RuntimeException("Error running " + scriptLocation,e);
		}
	}
	
	public static void initRequireInScope(Context cx, Scriptable scope) {
		runScript(cx, "/aure/jslib/initRequire.js", scope);
	}
	
	public static void addJavaObjectToScope(Scriptable scope, String name, Object obj) {
		ScriptableObject.putProperty(scope, name, Context.javaToJS(obj, scope) );
	}
	
	public static void main(String[] args) {
		Context cx = Context.enter();
		Scriptable scope = cx.initStandardObjects();
		addJavaObjectToScope(scope, "args", args);
		initRequireInScope(cx, scope);
		runScript(cx, "/" + args[0] + ".js", scope);
	}
}
